package com.lq.dubbo.rocketmq.shop.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lq.dubbo.rocketmq.shop.api.IGoodsService;
import com.lq.dubbo.rocketmq.shop.constant.ShopCode;
import com.lq.dubbo.rocketmq.shop.entity.Result;
import com.lq.dubbo.rocketmq.shop.exception.CastException;
import com.lq.dubbo.rocketmq.shop.mapper.TradeGoodsMapper;
import com.lq.dubbo.rocketmq.shop.mapper.TradeGoodsNumbersLogsMapper;
import com.lq.dubbo.rocketmq.shop.shop_pojo.TradeGoods;
import com.lq.dubbo.rocketmq.shop.shop_pojo.TradeGoodsNumbersLogs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: dubborocketmqshop
 * @description:
 * @author: LQ
 * @create: 2021-06-04 16:39
 */
@Component
@Service(interfaceClass = IGoodsService.class)
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    TradeGoodsMapper goodsMapper;

    @Autowired
    TradeGoodsNumbersLogsMapper goodsNumbersLogsMapper;

    @Override
    public TradeGoods findOne(Long goodsId) {
        if (goodsId == null) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        TradeGoods tradeGoods = goodsMapper.selectByPrimaryKey(goodsId);
        return tradeGoods;
    }

    @Override
    public Result reduceGoodsNum(TradeGoodsNumbersLogs goodsNumbersLogs) {
        if (goodsNumbersLogs == null || goodsNumbersLogs.getGoodsNumber() == null || goodsNumbersLogs.getGoodsId() == null || goodsNumbersLogs.getGoodsNumber().intValue() <= 0) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        TradeGoods goods = goodsMapper.selectByPrimaryKey(goodsNumbersLogs.getGoodsId());
        if (goods == null || goods.getGoodsNumber() < goodsNumbersLogs.getGoodsNumber()) {
            CastException.cast(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);
        }
        // 减库存
        goods.setGoodsNumber(goods.getGoodsNumber() - goodsNumbersLogs.getGoodsNumber());
        int i = goodsMapper.updateByPrimaryKey(goods);
        // 日志记录(因为增减都有日志记录,数量进行正负区分)
        goodsNumbersLogs.setGoodsNumber(-(goodsNumbersLogs.getGoodsNumber()));
        // 记录时间
        goodsNumbersLogs.setLogTime(new Date());
        int insert = goodsNumbersLogsMapper.insert(goodsNumbersLogs);
        return new Result(ShopCode.SHOP_SUCCESS.getSuccess(), ShopCode.SHOP_SUCCESS.getMessage());
    }
}
